<script>
import Taro from "@tarojs/taro";
import { reactive, watch } from "vue";
import { useTzRouter } from "@/vhooks/useTzRouter";
import { queryConsistPageApi, deleteConsistApi } from "./api";
import { getDicMap } from "@/utils/storage";
import { letgetDay } from "@/utils/date";
import TzVue, { useReachBottom, usePullDownRefresh } from "@/lib/TzVue";
import { useQueryForm } from "./useQueryForm";
import RecordList from "@/components/RecordList";
import { useRecordListConfig } from "../hooks/useRecordListConfig";

export default new TzVue({
  name: "ConfirmHome",
  components: { "record-list": RecordList },

  setup() {
    const { navigateTo, EventChannel, route } = useTzRouter();
    const { inOutTypeDic, customsCode, statusDic } = getDicMap();

    EventChannel.on(route.path, (event) => {
      if (event?.type === "backRefresh") {
        // 刷新数据
        queryConfirmData({
          beginTime: letgetDay(-state.activedTabName),
          currentPage: 1,
          endTime: letgetDay(0),
        });
      }
    });

    //下拉刷新
    usePullDownRefresh(() => {
      const { activedTabName } = state;
      if (activedTabName !== "other") {
        const params = {
          beginTime: letgetDay(-activedTabName),
          currentPage: 1,
          endTime: letgetDay(0),
        };
        queryConfirmData(params);
      }
      Taro.stopPullDownRefresh();
    });

    useReachBottom(() => {
      const { activedTabName } = state;
      if (activedTabName !== "other") {
        const params = {
          beginTime: letgetDay(-activedTabName),
          currentPage: ++state.currentPage,
          endTime: letgetDay(0),
        };
        queryConfirmData(params, true);
      }
    });

    const state = reactive({
      activedTabName: "7",
      currentPage: 1,
      confirmDataList: [],
      queryForm: {
        customsCode: "", // 口岸代码
        docCode: "", // 六联单号
        inOutType: "", // 单据类型
        status: "", // 单据状态
        driverName: "", // 司机姓名
        beginTime: "", // 录单时间
        endTime: "", // 录单结束时间
      },
    });

    // loading watcher
    watch(
      () => state.showLoading,
      (newVal) => {
        newVal
          ? Taro.showLoading({
              title: "加载中",
            })
          : Taro.hideLoading();
      }
    );

    // 查询确报数据
    const queryConfirmData = (params, isAppend) => {
      if (state.showLoading) return;
      state.showLoading = true;
      return new Promise((resolve, reject) => {
        queryConsistPageApi(params)
          .then((res) => {
            state.showLoading = false;
            const { recordList, pageCount } = res.data;
            if (isAppend) {
              if (state.currentPage > pageCount) {
                Taro.showToast({
                  title: "已全部加载完成",
                  icon: "none",
                  duration: 2000,
                });
                // 把页数重置为上一页
                state.currentPage--;
                return;
              }
              state.confirmDataList.push(...recordList);
            } else {
              state.confirmDataList = recordList;
            }
            resolve();
          })
          .catch((err) => {
            state.showLoading = false;
            reject(err);
          });
      });
    };

    // 首次加载确报列表
    queryConfirmData({
      beginTime: letgetDay(-state.activedTabName),
      currentPage: 1,
      endTime: letgetDay(0),
    });

    const queryFormRender = useQueryForm(state, getDicMap, navigateTo);

    // 海关确报查询
    const toConfirmCheck = () => {
      navigateTo({
        path: "/pages/subUser/webPage/index",
        query: {
          url:
            "https://xcxceshi.sztaizhou.com/site2/mnftq/MRoadTransportQuery.aspx",
          title: "海关确报查询",
        },
      });
    };

    const handleBtnClick = (data) => {
      if (["receipt", "receiptAndShot"].indexOf(data.hanldeName) !== -1) {
        const { consistId: consistid, inOutType, consistStatus } = data.data;

        navigateTo({
          path: "/pages/subCN/confirm/receipt/index",
          query: {
            consistid,
            inOutType: inOutTypeDic[inOutType],
            consistStatus,
          },
        });
      } else if (data.hanldeName === "delete") {
        const { consistId } = data.data;
        console.log(consistId);
        Taro.showModal({
          content: "确定删除该条记录吗?",
          confirmText: "确定",
          cancelText: "取消",
        })
          .then((res) => {
            return res.confirm ? deleteConsistApi(consistId) : false;
          })
          .then(() => {
            const params = {
              beginTime: letgetDay(-state.activedTabName),
              currentPage: 1,
              endTime: letgetDay(0),
            };
            queryConfirmData(params);
          });
      }
    };

    const listItemClick = (data) => {
      navigateTo({
        path: "/pages/subCN/confirm/details/index",
        query: { consistId: data.consistId },
      });
    };

    /**
     * NOTE:
     * handleData2Cell 确报列表页左侧数据配置
     * cellRightDataConfig 确报列表页右侧数据配置
     * 这两个传入 RecordList 组件，在里面接收传入的 dataList 匹配到对应的数据
     */
    const { handleData2Cell, cellRightDataConfig } = useRecordListConfig(
      inOutTypeDic,
      customsCode,
      statusDic
    );
    /**
     * onBtnClick 右侧按钮点击
     * listItemClick 列表项点击（点击范围在左侧文本区域）
     */
    const recordListRender = () => {
      return state.confirmDataList.length ? (
        <record-list
          dataList={state.confirmDataList}
          cellList={handleData2Cell}
          onBtnClick={handleBtnClick}
          onItemClick={listItemClick}
          cellRightDataConfig={cellRightDataConfig}
        ></record-list>
      ) : (
        <tz-view class="none-data">查询结果为空</tz-view>
      );
    };

    const handleTabClick = (tabName) => {
      if (tabName !== "other") {
        state.currentPage = 1;
        const params = {
          beginTime: letgetDay(-tabName),
          currentPage: 1,
          endTime: letgetDay(0),
        };
        queryConfirmData(params);
      }
    };

    return () => {
      return (
        <tz-view class="confirm-home">
          <tz-view class="tip-board">
            <tz-icon class="tip-icon" name="tips"></tz-icon>
            <tz-view class="tip-text">
              <tz-view>
                超十分钟无回执,点击
                <tz-text class="link-btn" onClick={() => toConfirmCheck()}>
                  海关确报查询
                </tz-text>
              </tz-view>
              <tz-view>数据显示未核销,则捆绑成功可过关</tz-view>
            </tz-view>
          </tz-view>
          <tz-tabs v-model={state.activedTabName} onTabClick={handleTabClick}>
            <tz-tab-pane label="七天内" name="7">
              {recordListRender()}
            </tz-tab-pane>
            <tz-tab-pane label="一个月内" name="30">
              {recordListRender()}
            </tz-tab-pane>
            <tz-tab-pane label="条件查询" name="other">
              {queryFormRender()}
            </tz-tab-pane>
          </tz-tabs>
        </tz-view>
      );
    };
  },
});
</script>

<style lang="scss">
.confirm-home {
  display: flex;
  align-items: center;
  flex-direction: column;
  .tip-board {
    display: flex;
    font-size: 15px;
    width: 100%;
    justify-content: center;
    padding: 10px 0;
    background: beige;
    .tip-icon {
      font-size: 15px;
      color: $danger-color;
      margin-right: 2px;
    }
    .tip-text {
      > .tz-view {
        &:first-child {
          margin-bottom: 5px;
        }
      }
    }
    .link-btn {
      color: $success-color;
    }
  }

  .tz-tabs {
    .none-data {
      text-align: center;
      font-size: 15px;
      color: $text-color;
    }
  }

  .query-block {
    display: flex;
    flex-direction: column;
    .query-form {
      background-color: $white;
      padding: 0 15px;
      .tz-cell {
        &:last-child:after {
          border: none;
        }
        picker {
          .placeholder {
            color: $placeholder-color;
          }
        }
        .tz-icon-scan {
          color: $info-color-active;
        }
      }
    }
    .search-btn {
      align-self: center;
      width: 345px;
      margin-top: 20px;
      height: 44px;
    }
  }
}
</style>
